package com.fh.shop.biz;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fh.shop.Order;
import com.fh.shop.OrderDetail;
import com.fh.shop.common.Constant;
import com.fh.shop.common.ResponseEnum;
import com.fh.shop.mapper.IOrderDetailMapper;
import com.fh.shop.mapper.IOrderMapper;
import com.fh.shop.mapper.IProductMapper;
import com.fh.shop.util.ServerResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service("orderCommonService")
public class IOrderCommonServiceImpl implements IOrderCommonService {

    @Autowired
    private IOrderDetailMapper orderDetailMapper;
    @Autowired
    private IProductMapper productMapper;
    @Autowired
    private IOrderMapper orderMapper;

    @Override
    public ServerResponse cancelOrder(String orderId) {
        //验证订单是否存在
        Order order = orderMapper.selectById(orderId);
        if (order == null){
            return ServerResponse.error(ResponseEnum.ORDER_INFO_IS_NULL);
        }

        //验证订单状态 防止幂等性重复取消
        if (order.getOrderStatus() > Constant.OrderStatus.WAIT_PAY){
            return ServerResponse.error(ResponseEnum.ORDER_CANCEL_IS_ERROR);
        }

        //更新订单状态
        Order order1 = new Order();
        order1.setId(orderId);
        order1.setOrderStatus(Constant.OrderStatus.PAY_ERROR);
        orderMapper.updateById(order1);

        //归还库存
        QueryWrapper<OrderDetail> queryWrapper = new QueryWrapper<>();
        queryWrapper
                .select("productId","count")
                .eq("orderId",order.getId());
        List<OrderDetail> orderDetailList = orderDetailMapper.selectList(queryWrapper);
        orderDetailList.forEach(x -> {
            productMapper.updateStock(x.getProductId(),x.getCount() * (-1));
        });
        return ServerResponse.success();
    }
}
